package com.nmcc.app_adherence;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
//import java.util.Arrays;
import java.util.Iterator;
import java.util.Scanner;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;
import java.nio.channels.FileChannel;

public class MergeCSV {
	private static String folderLocationInSDCardBluetoothForToday;
	private static int countoffilesmergedsuccessfully;
	
	public void launchProcedure(Context context,int GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8){
        String idFile = "GPSData";
        String idFilePersons = "Persons";
        int numFiles = 300;//can do up to 100 files can add more later
        //int countoffilesmergedsuccess;
        
        Calendar c = Calendar.getInstance();
 	   int day = c.get(Calendar.DAY_OF_MONTH);
			   int year = c.get(Calendar.YEAR);
			   int currentmonth = c.get(Calendar.MONTH);
			   folderLocationInSDCardBluetoothForToday ="/bluetooth/"+ day + "-" + currentmonth + "-" + year + "-GPS/";
		//end here for the 
        
        
        try {
            //check if need call whole procedure for copy of nets, hhold, membmers, malaria below
        	
        	 if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==1 || GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==2 || GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==8) 
             {
        		 //gps housedata
        		 if (gpsfilespresent(context,folderLocationInSDCardBluetoothForToday)){
            		 mergeCsvFiles(idFile, numFiles, context,GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8);
                 }
         	 }
        	 //persons
          else if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==3 || GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==4 || GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==5 || GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==6 || GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==7) 
         	 {
        	  	 if (Personsfilespresent(context,folderLocationInSDCardBluetoothForToday)){
     	       		mergeCsvFiles(idFilePersons, numFiles, context,GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8);
     	         }       
         	 } 
             	
   	 
        } catch (IOException e) {
            e.printStackTrace();
        }
        
	}
	
	
   // public static void main(String[] args) {
      //removed the code here
    //}

    private static void mergeCsvFiles(String idFile, int numFiles,Context context, int GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8 ) throws IOException {
    		//my variables here
    	//String sdcardBluetoothFolderWithSlash =Environment.getExternalStorageDirectory() + "Bluetooth\"; 
		//get ///sdcard/
   	
    	
        // Variables
        ArrayList<File> files = new ArrayList<File>();
        Iterator<File> iterFiles;
        File fileOutput;
        
        BufferedWriter fileWriter;
        BufferedReader fileReader;
        String csvFile;
        String csvFinal;
        //put the csv file as appropriately
        
      	//check in toda'ys date 3-3-2014 folder
			   //String folderLocationInSDCardBluetooth ="/bluetooth/"+ day + "-" + currentmonth + "-" + year + "-GPSDATA/";
		//end here for the 
        
        //  //String csvFinal = "C:\\out\\" + idFile + ".csv";
        //gps houses data
        if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==1) 
        {
        	// + "/opendatakit/survey/tables/household/forms/Adherence_Phone_1/GPSData.csv"
            csvFinal = Environment.getExternalStorageDirectory().toString() + "/opendatakit/survey/tables/household2/forms/Adherence_Phone_2/" + idFile + ".csv";

    	 }
     else if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==2) 
    	 {
         csvFinal = Environment.getExternalStorageDirectory().toString() + folderLocationInSDCardBluetoothForToday + idFile + " Master.csv";

    	 } 
        //persons
     else if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==3) 
         {
    	 csvFinal = Environment.getExternalStorageDirectory().toString() + "/opendatakit/survey/tables/household_member/forms/member_adherence/" + idFile + ".csv";

    	 } 
     else if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==4) 
     {
         csvFinal = Environment.getExternalStorageDirectory().toString() + folderLocationInSDCardBluetoothForToday + idFile + " Master.csv";

	 } 
        
   //members
     else if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==6) 
     {
       	 csvFinal = Environment.getExternalStorageDirectory().toString() + "/opendatakit/survey/tables/household_member/forms/member_adherence/" + idFile + ".csv";

	 } 
            
   //nets
     else if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==5) 
     {
       	 csvFinal = Environment.getExternalStorageDirectory().toString() + "/opendatakit/survey/tables/household_nets/forms/nets/" + idFile + ".csv";

	 } 
             
        
   //malaria
     else if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==7) 
     {
       	 csvFinal = Environment.getExternalStorageDirectory().toString() + "/opendatakit/survey/tables/household_member/forms/malaria/" + idFile + ".csv";

	 } 
            
        
   //household new
        
     else if (GPSGiveOdkAs1DontTakeAs2PersonsGiveOdkAs3DontTakeAs4Net5Mem6Mal7Hshnew8==8) 
     {
    	  csvFinal = Environment.getExternalStorageDirectory().toString() + "/opendatakit/survey/tables/household/forms/household_new/" + idFile + ".csv";

	 } 
            
    
     else 
         {
    	 throw new IllegalArgumentException();
    	 }

        //String csvFinal = Environment.getExternalStorageDirectory().toString() + "/bluetooth/" + idFile + ".csv";
        // + "/opendatakit/survey/tables/household/forms/Adherence_Phone_1/GPSData.csv"
        
        String[] headers = null;
        String header = null;

        Toast.makeText(context, "The files must be names e.g GPSData_1.csv, GPSData_2.csv, .... The output is GPSData.csv in the bluetooth folder.", Toast.LENGTH_LONG).show();
        
        
        // Files: Input
        for (int i = 0; i <= numFiles; i++) {
            //csvFile = "C:\\in\\" + idFile + "#" + i + "_" + numFiles + ".csv";

	        	if (i==0) {//only at first time also get GPSData.csv or Persons.csv since first phone sends this file
	        		csvFile = Environment.getExternalStorageDirectory().toString() + folderLocationInSDCardBluetoothForToday + idFile + ".csv";
         
	        	}
		    	 else{
		    		 csvFile = Environment.getExternalStorageDirectory().toString() + folderLocationInSDCardBluetoothForToday + idFile + "_" + i + ".csv";
		    	 }
	        
	        	
	        	
            boolean alreadyExists = new File(csvFile).exists();
            if (alreadyExists) {
            	
            	files.add(new File(csvFile));
            	
            	countoffilesmergedsuccessfully=countoffilesmergedsuccessfully + 1;
            }
        }

        	
		//countoffilesmergedsuccessfully
    	
    	//Toast.makeText(context, "Number of files merged successfully: " + countoffilesmergedsuccessfully, Toast.LENGTH_LONG).show();
        
        // Files: Output
        fileOutput = new File(csvFinal);
        if (fileOutput.exists()) {
            fileOutput.delete();
        }
        try {
            fileOutput.createNewFile();
            // log
            // System.out.println("Output: " + fileOutput);
        } catch (IOException e) {
            // log
        }

        iterFiles = files.iterator();
        fileWriter = new BufferedWriter(new FileWriter(csvFinal, true));

        // Headers
        Scanner scanner = new Scanner(files.get(0));
        if (scanner.hasNextLine())
            header = scanner.nextLine();
        // if (scanner.hasNextLine()) headers = scanner.nextLine().split(";");
        scanner.close();

        /*
         * System.out.println(header); for(String s: headers){
         * fileWriter.write(s); System.out.println(s); }
         */

        fileWriter.write(header);
        fileWriter.newLine();

        while (iterFiles.hasNext()) {

            String line;// = null;
            String[] firstLine;// = null;

            File nextFile = iterFiles.next();
            fileReader = new BufferedReader(new FileReader(nextFile));

            if ((line = fileReader.readLine()) != null)
                firstLine = line.split(";");

            while ((line = fileReader.readLine()) != null) {
                fileWriter.write(line);
                fileWriter.newLine();
            }
            fileReader.close();
        }

        fileWriter.close();
        
        Toast.makeText(context, countoffilesmergedsuccessfully + " CSV Files successfully merged. Please copy the merged file GPSData.csv from the bluetooth folder into sdcard/opendatakit/survey/tables/household2/forms/Adherence_Phone_2. ", 5000).show();

    }

    
    public boolean Personsfilespresent(Context context, String TodaysFolderName){
           boolean alreadyExists2 = new File(Environment.getExternalStorageDirectory().toString() + TodaysFolderName + "Persons_1.csv").exists();
           boolean alreadyExists3 = new File(Environment.getExternalStorageDirectory().toString() + TodaysFolderName + "Persons.csv").exists();
           boolean result=false;   
        if (alreadyExists2) {
        	result= true;
          }
        if (alreadyExists3) {
        	result= true;
          } 
        
        if (!result){
        	Toast.makeText(context, "Please make sure that the bluetooth folder contains Persons_1.csv,Persons_2.csv...files in order for you to proceed.", Toast.LENGTH_LONG).show();
            // Files: Input
        	//result= false;
        }
        
        
        
        return result;
        
    }
    
 
    public boolean gpsfilespresent(Context context, String TodaysFolderName){
        boolean alreadyExists = new File(Environment.getExternalStorageDirectory().toString() + TodaysFolderName + "GPSData_1.csv").exists();
        boolean alreadyExists1 = new File(Environment.getExternalStorageDirectory().toString() + TodaysFolderName + "GPSData.csv").exists();
        boolean result=false; 
        if (alreadyExists) {
        	result= true;
          }
        if (alreadyExists1) {
        	result= true;
          } 
        
        if (!result){
     	Toast.makeText(context, "Please make sure that the bluetooth folder contains GPSData_1.csv, GPSData_2.csv,...files in order for you to proceed.", Toast.LENGTH_LONG).show();
         // Files: Input
     	//return false;
        }
        return result;

 } 
  
    public void DeleteAllFilesInBluetoothFolder(View view){
    	//copy csv files into a e.g 3-3-2014 folder
    	File sdcard = Environment.getExternalStorageDirectory();

    		//String csvFile;
    		int numFiles=300;
    		String CSVfilenameGPS;
    		String CSVfilenamePersons;
    		
            // Files: Input
            for (int i = 0; i <= numFiles; i++) {
            	
            	if (i==0) {//only at first time also get GPSData.csv or Persons.csv since first phone sends this file
            		CSVfilenameGPS="GPSData.csv";
            		CSVfilenamePersons="Persons.csv";
		    	 }
		    	 else{
		    		 CSVfilenameGPS="GPSData_" + i + ".csv";
		    		 CSVfilenamePersons="Persons_" + i + ".csv";
		    	 }
            	
            	//number 1 either gpsdata or persons do together for num N
            	//Do for GPSData
            	//String CSVfilenameGPS="GPSData(" + i + ").csv";
            	File fSource=new File(sdcard+ "/bluetooth/" + CSVfilenameGPS);
            	//check if file exists
                	 boolean alreadyExists = new File(Environment.getExternalStorageDirectory().toString() + "/bluetooth/" + CSVfilenameGPS).exists();
   	          
                	 if (alreadyExists) {
                		 	boolean deleted = fSource.delete();
                	 }
                	 else{
   	        	  		//do nothing
                	 }
                //end of gpsdata copying
                	 
                //Do for Persons file
                    //String CSVfilenamePersons="Persons(" + i + ").csv";
                    File fSourcePersons=new File(sdcard+ "/bluetooth/" + CSVfilenamePersons);
                    //check if file exists
	                boolean alreadyExistsPersons = new File(Environment.getExternalStorageDirectory().toString() + "/bluetooth/" + CSVfilenamePersons).exists();
           	          
	                if (alreadyExistsPersons) {
	                	boolean deleted = fSourcePersons.delete();
	                }
	                   else{
           	        	 //do nothing
	                }
	            //end of persons data copying
                	 
            }
    	
    }
    
    
    
    public void CopyMergedMasterFileToODKSurvey(View view){
    	//copy csv files into a e.g 3-3-2014 folder
    	File sdcard = Environment.getExternalStorageDirectory();
    		String CSVfilenameGPS="GPSData Master.csv";
    		String CSVfilenamePersons="Persons Master.csv";
    		
    		
    		try
    		{
    			
    			renameAllCSVFilesInOdkFoldersBeforeMerge(view);
    			
            // Files: Input
            	//Do for GPSData
            	//String CSVfilenameGPS="GPSData(" + i + ").csv";
            	
    			String CSVPathOfFinalODKMasterGPSFile=sdcard+ folderLocationInSDCardBluetoothForToday + CSVfilenameGPS;
    			
    			File fSource=new File(sdcard+ folderLocationInSDCardBluetoothForToday + CSVfilenameGPS);
            	File fDestin1=new File(sdcard + "/opendatakit/survey/tables/household2/forms/Adherence_Phone_2/GPSData.csv");
            	//File fDestin2=new File(sdcard + "/opendatakit/survey/tables/household/forms/household_new/GPSData.csv");
            	//check if file exists
                	 boolean alreadyExists = new File(sdcard + folderLocationInSDCardBluetoothForToday + CSVfilenameGPS).exists();
                	 		boolean copygpsdatadone=false;
   	           
                	 if (alreadyExists) {
                		 
                		 	copyFileUsingFileChannels(fSource,fDestin1);
                		 	//copyFileUsingFileChannels(fSource,fDestin2);
                		 	copygpsdatadone=true;
                		 	
                	 }
                	 else{
   	        	  		//do nothing
                	 }
                //end of gpsdata copying
                	 
                //Do for Persons file
                    //String CSVfilenamePersons="Persons(" + i + ").csv";
                    File fSourcePersons=new File(sdcard+ folderLocationInSDCardBluetoothForToday + CSVfilenamePersons);
                    //File fDestinPersons1=new File(sdcard + "/opendatakit/survey/tables/household_member/forms/malaria/Persons.csv");
                    File fDestinPersons2=new File(sdcard + "/opendatakit/survey/tables/household_member2/forms/member_adherence/Persons.csv");
                   // File fDestinPersons3=new File(sdcard + "/opendatakit/survey/tables/household_member/forms/member/Persons.csv");
                    //File fDestinPersons4=new File(sdcard + "/opendatakit/survey/tables/household_nets/forms/nets/Persons.csv");
                    //check if file exists
	                boolean alreadyExistsPersons = new File(Environment.getExternalStorageDirectory().toString() + folderLocationInSDCardBluetoothForToday + CSVfilenamePersons).exists();
           	         
           	          
	                if (alreadyExistsPersons) {
	                    	//copyFileUsingFileChannels(fSourcePersons,fDestinPersons1);
	                    	copyFileUsingFileChannels(fSourcePersons,fDestinPersons2);
	                    	//copyFileUsingFileChannels(fSourcePersons,fDestinPersons3);
	                    	//copyFileUsingFileChannels(fSourcePersons,fDestinPersons4);
	                }
	                   else{
           	        	 //do nothing
	                }
	            //end of persons data copying
	                
	                //now send to odk survey
	                
	                
	                if (copygpsdatadone){
	                	sendCSVToDatabase(CSVPathOfFinalODKMasterGPSFile);
	                }
	                
		    }
		 	catch(IOException e)
		 	{
		 	     e.printStackTrace();
		 	} 
    	
    } 
    
    
	   private static void copyFileUsingFileChannels(File source, File dest)
	   	        throws IOException {
	   	    FileChannel inputChannel = null;
	   	    FileChannel outputChannel = null;
	   	    try {
	   	        inputChannel = new FileInputStream(source).getChannel();
	   	        outputChannel = new FileOutputStream(dest).getChannel();
	   	        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
	   	    } finally {
	   	        inputChannel.close();
	   	        outputChannel.close();
	   	    }
	   	}
    
	   public static void renameFile(String oldName, String newName){
		   File dir = Environment.getExternalStorageDirectory();
		   if (dir.exists()){
			   File from=new File(dir, oldName);
			   
			   File to = new File(dir, newName);
			   if(from.exists())
				   from.renameTo(to);
			   
			   
		   }
	   }
	   
	   public void renameAllCSVFilesInOdkFoldersBeforeMerge(View view){

	        Calendar c = Calendar.getInstance();
	        
	        int hour = c.get(Calendar.HOUR);
			   int min = c.get(Calendar.MINUTE);
			   int second = c.get(Calendar.SECOND);
	 	   int day = c.get(Calendar.DAY_OF_MONTH);
				   int year = c.get(Calendar.YEAR);
				   int currentmonth = c.get(Calendar.MONTH);
				  String AddInfonewfilenameToday =day + "-" + currentmonth + "-" + year + "--" + hour + "-" + min + "-" + second;
			//end here for the 
	    	//copy csv files into a e.g 3-3-2014 folder
	    	File sdcard = Environment.getExternalStorageDirectory();
	    		
	    	
	    	
	    		//try
	    		//{
	            // Files: Input
	            	//Do for GPSData adherence
	            	//String CSVfilenameGPS="GPSData(" + i + ").csv";
	            	File fadhfrom=new File(sdcard + "/opendatakit/survey/tables/household2/forms/Adherence_Phone_2/GPSData.csv");
	            	File fadhTo=new File(sdcard + "/opendatakit/survey/tables/household/forms/Adherence_Phone_1/GPSData " + AddInfonewfilenameToday + ".csv");
	            	//check if file exists
	                	 boolean alreadyExistsAdher = new File(sdcard + "/opendatakit/survey/tables/household2/forms/Adherence_Phone_2/GPSData.csv").exists();
	   	          
	                	 if (alreadyExistsAdher) {
	                		 
	                		 fadhfrom.renameTo(fadhTo);
	                	 }
	                	 else{
	   	        	  		//do nothing
	                	 }
	                	 
	                	 //do for household new
	                		File fhhnewfrom=new File(sdcard + "/opendatakit/survey/tables/household/forms/household_new/GPSData.csv");
	    	            	File fhhnewTo=new File(sdcard + "/opendatakit/survey/tables/household/forms/household_new/GPSData " + AddInfonewfilenameToday + ".csv");
	    	            	//check if file exists
	    	                	 boolean alreadyExistsHHNew = new File(sdcard + "/opendatakit/survey/tables/household/forms/household_new/GPSData.csv").exists();
	    	   	          
	    	                	 if (alreadyExistsHHNew) {
	    	                		 
	    	                		 fhhnewfrom.renameTo(fhhnewTo);
	    	                	 }
	    	                	 else{
	    	   	        	  		//do nothing
	    	                	 }	                	 
	                	 
	                //end of gpsdata copying
	                	 
	                //Do for Persons file
	                    //String CSVfilenamePersons="Persons(" + i + ").csv";
	                    //malaria
                		File fmalarnewfrom=new File(sdcard + "/opendatakit/survey/tables/household_member/forms/malaria/Persons.csv");
    	            	File fmalarnewTo=new File(sdcard + "/opendatakit/survey/tables/household_member/forms/malaria/Persons " + AddInfonewfilenameToday + ".csv");
    	            	//check if file exists
    	                	 boolean alreadyExistsmalar = new File(sdcard + "/opendatakit/survey/tables/household_member/forms/malaria/Persons.csv").exists();
    	   	          
    	                	 if (alreadyExistsmalar) {
    	                		 
    	                		 fmalarnewfrom.renameTo(fmalarnewTo);
    	                	 }
    	                	 else{
    	   	        	  		//do nothing
    	                	 }	                	 
                	           
	                    
	    	            //member adherence
                		File fmembAdhernewfrom=new File(sdcard + "/opendatakit/survey/tables/household_member/forms/member_adherence/Persons.csv");
    	            	File fmembAdhernewTo=new File(sdcard + "/opendatakit/survey/tables/household_member/forms/member_adherence/Persons " + AddInfonewfilenameToday + ".csv");
    	            	//check if file exists
    	                	 boolean alreadyExistsmembAdher = new File(sdcard + "/opendatakit/survey/tables/household_member/forms/member_adherence/Persons.csv").exists();
    	   	          
    	                	 if (alreadyExistsmembAdher) {
    	                		 
    	                		 fmembAdhernewfrom.renameTo(fmembAdhernewTo);
    	                	 }
    	                	 else{
    	   	        	  		//do nothing
    	                	 }	                	 
                	            
	                    //member
                		File fmembernewfrom=new File(sdcard + "/opendatakit/survey/tables/household_member/forms/member/Persons.csv");
    	            	File fmembernewTo=new File(sdcard + "/opendatakit/survey/tables/household_member/forms/member/Persons " + AddInfonewfilenameToday + ".csv");
    	            	//check if file exists
    	                	 boolean alreadyExistsmember = new File(sdcard + "/opendatakit/survey/tables/household_member/forms/member/Persons.csv").exists();
    	   	          
    	                	 if (alreadyExistsmember) {
    	                		 
    	                		 fmembernewfrom.renameTo(fmembernewTo);
    	                	 }
    	                	 else{
    	   	        	  		//do nothing
    	                	 }	                	 
                	 
		            //household nets
    	                	 //member
    	                		File fnetsnewfrom=new File(sdcard + "/opendatakit/survey/tables/household_nets/forms/nets/Persons.csv");
    	    	            	File fnetsnewTo=new File(sdcard + "/opendatakit/survey/tables/household_nets/forms/nets/Persons " + AddInfonewfilenameToday + ".csv");
    	    	            	//check if file exists
    	    	                	 boolean alreadyExistsnets = new File(sdcard + "/opendatakit/survey/tables/household_nets/forms/nets/Persons.csv").exists();
    	    	   	          
    	    	                	 if (alreadyExistsnets) {
    	    	                		 
    	    	                		 fnetsnewfrom.renameTo(fnetsnewTo);
    	    	                	 }
    	    	                	 else{
    	    	   	        	  		//do nothing
    	    	                	 }	                	 
    	                	 
			    //}
			 	//catch(IOException e)
			 	//{
			 	    /// e.printStackTrace();
			 	//} 
	    	
	    } 

	   
	   public boolean sendCSVToDatabase(String fileName){
			 
			 SQLiteDatabase db;
			 
	  			String dir = Environment.getExternalStorageDirectory().getPath();
	  			File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
	  			db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);


			 try {
				FileReader file = new FileReader(fileName);
				  			BufferedReader buffer = new BufferedReader(file);
				  			String line = "";
		
	  			//db.beginTransaction();
	  			while ((line = buffer.readLine()) != null) {
	  			    //StringBuilder sb = new StringBuilder(str1);
	  			    String[] str = line.split(",");
	  			    
	  			  ContentValues cv = new ContentValues();
		        	cv.put("_id", str[0]);
		        	cv.put("_sync_state", "new_row"); 
		        	 cv.put("_form_id", "gpsdata_new"); 
		        	 cv.put("_locale", "default"); 
		        	cv.put("_savepoint_timestamp", str[3]); //redo time need .89000000000
		        	cv.put("_savepoint_creator", "anonymous"); 
	        	    //housedetails
		        	cv.put("HouseID", str[0]); 
		        	cv.put("HouseNumber", str[1]); 
		        	cv.put("ClusterNumber", str[2]); 
		        	cv.put("DateTaken", str[3]); 
		        	cv.put("PlaceName", str[5]); 
		        	cv.put("HHResult", str[6]); 
		        	cv.put("HHResultOther", str[7]); 
		        	cv.put("HHResultLabel", str[8]); 
		        	cv.put("comment", str[9]);
		        	cv.put("Longitude", str[10]);
		        	cv.put("Latitude", str[11]);
		        	cv.put("HDOP", str[12]);
		        	cv.put("household_id", str[13]);
		        	String fullhousename=str[1]+ "." + str[9] + "." + str[5] + " | " + str[3];
		        
		        	cv.put("fullhousename", fullhousename);
		        	cv.put("DueForFollowUp", "1");//not yet followed up
		        	
		        	if (!str[1].equals("HouseNumber")){//its not a heading
		        		db.insert("gpsdata", null, cv);
		        	}
		        	  

		        	 // db.close();
		          }

			
		          db.close(); 
	

		          return true;
		        } catch(Exception e) {
		            e.printStackTrace();
		            return false;
		        }
			
			
			
	}
	   

	   public boolean sendCSVToDatabaseOld(String fileName){
			 
			 SQLiteDatabase db;
			 
	  			String dir = Environment.getExternalStorageDirectory().getPath();
	  			File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
	  			db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);


			 try {
				FileReader file = new FileReader(fileName);
				  			BufferedReader buffer = new BufferedReader(file);
				  			String line = "";
				  			String tableName ="gpsdata";
				  			String columns = "_id,_sync_state,_form_id,_locale,_savepoint_timestamp,_savepoint_creator,HouseID,HouseNumber,ClusterNumber,DateTaken,PlaceName,HHResult,HHResultOther,HHResultLabel,comment,Longitude,Latitude,HDOP,household_id";
				  			String str1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
				  			String str2 = ");";
				 
	  			db.beginTransaction();
	  			while ((line = buffer.readLine()) != null) {
	  			    StringBuilder sb = new StringBuilder(str1);
	  			    String[] str = line.split(",");
	  			    sb.append("'" + str[0] + "','");
	  			    sb.append("new_row" + "','");
	  			    sb.append("gpsdata_new" + "','");
	  			    sb.append("default" + "','");
	  			    sb.append(str[3] + "','");
		  			sb.append("anonymous" + "','");
		  			sb.append(str[0] + "',");
		  			sb.append(str[1] + ",");
		  			sb.append(str[2] + ",'");
		  			sb.append(str[3] + "','");
		  			sb.append(str[4] + "','");
		  			sb.append(str[5] + "','");
		  			sb.append(str[6] + "','");
		  			sb.append(str[7] + "','");
		  			sb.append(str[8] + "','");
		  			sb.append(str[9] + "',");
		  			sb.append(str[10] + ",'");
		  			sb.append(str[11] + "'");
	  			    sb.append(str2);
	  			    db.execSQL(sb.toString());
	  			}
	  			db.setTransactionSuccessful();
	  			db.endTransaction();
				 

		          return true;
		        } catch(Exception e) {
		            e.printStackTrace();
		            return false;
		        }
			
			
			
	}
	   

	   
}
